<template>
    <div>
        <!-- <h3>用户列表组件</h3> -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card >
            
            <el-row :gutter="10">
                <el-col :span="7">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList" >
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"
                        ></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <el-table
                :data="userList"
                stripe
                border
                style="width: 100%">
                <el-table-column
                    type="index">
                </el-table-column>
                <el-table-column
                    prop="username"
                    label="姓名">
                </el-table-column>
                <el-table-column
                    prop="email"
                    label="邮箱">
                </el-table-column>
                <el-table-column
                    prop="mobile"
                    label="电话">
                </el-table-column>
                <el-table-column
                    prop="role_name"
                    label="角色">
                </el-table-column>
                <el-table-column
                    label="状态">
                    <template slot-scope="scope">
                        <el-switch
                            v-model="scope.row.mg_state"
                            @change="userStateChanged(scope.row)">
                        </el-switch>
                        <!-- {{ scope.row.mg_state }} -->
                    </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    width="180">
                    <template slot-scope="scope">
                        <!-- 修改 -->
                        <el-tooltip effect="dark" content="修改角色" placement="top" :enterable="false">
                            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row)"></el-button>
                        </el-tooltip>
                        <!-- 删除 -->
                        <el-tooltip effect="dark" content="删除角色" placement="top" :enterable="false">
                            <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeUserById(scope.row)"></el-button>
                        </el-tooltip>
                        <!-- 分配角色 -->
                        <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button size="mini" type="warning" icon="el-icon-setting" @click="setting(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[1, 2, 5, 10]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>
        <el-dialog
            title="添加用户"
            :visible.sync="addDialogVisible"
            width="50%"
            @close="addDialogClosed">
            <el-form :model="addUserForm" :rules="addUserRules" ref="addUserRef" label-width="70px" >
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addUserForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addUserForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addUserForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog
            title="修改用户"
            :visible.sync="editDialogVisible"
            width="50%"
            @close="editDialogClosed">
            <el-form :model="editUserForm" :rules="editUserRules" ref="editUserRef" label-width="70px" >
                <el-form-item label="用户名">
                    <el-input v-model="editUserForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="editUserForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog
            title="分配角色"
            :visible.sync="setRoleDialogVisible"
            width="50%"
            @close="setRoleDialogClosed">
            <!-- <el-tree ref="treeRef" node-key="id" show-checkbox default-expand-all  :data="rightsList" :props="defaultProps" @node-click="handleNodeClick"></el-tree> -->
            <div>
                <p>当前用户：{{ userInfo.username }}</p>
                <p>当前角色：{{ userInfo.role_name }}</p>
                <p>分配角色：
                    <el-select v-model="roleId" placeholder="请选择">
                        <el-option
                        v-for="item in rolesList"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id">
                        </el-option>
                </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoleDialogVisible = false" size="mini">取 消</el-button>
                <el-button type="primary" @click="setRoles" size="mini">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data(){
        var checkEmail = (rule,value,cb)=>{
            const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
            if(regEmail.test(value)){
                cb()
            }else{
                cb(new Error('请输入合法的邮箱'))
            }
        };
        var checkMobile = (rule,value,cb)=>{
            const regMobile = /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/
            if(regMobile.test(value)){
                cb()
            }else{
                cb(new Error('请输入合法的手机号码'))
            }
        };
        return{
            queryInfo:{
                query:'',
                pagenum:1,
                pagesize:1
            },
            userList:[],
            total:0,
            // 隐藏对话框
            addDialogVisible:false,
            addUserForm:{
                username:'',
                password:'',
                email:'',
                mobile:''
            },
            addUserRules:{
                username:[
                    {
                        required:true,
                        message:'name',
                        trriger:'blur'

                    },
                    {
                        min:3,
                        max:10,
                        message:'3-10',
                        trriger:'blur'
                    }
                ],
                password:[
                    {
                        required:true,
                        message:'password',
                        trriger:'blur'
                    }
                ],
                email:[
                    {
                        required:true,
                        message:'请输入email',
                        trriger:'blur'
                    },
                    {
                        validator:checkEmail,
                        trriger:'blur'
                    }
                ],
                mobile:[
                    {
                        required:true,
                        message:'请输入手机号码',
                        trriger:'blur'
                    },
                    {
                        validator:checkMobile,
                        trriger:'blur'
                    }
                ],
                
            },
            editUserForm:{
                id:'',
                username:'',
                password:'',
                email:'',
                mobile:''
            },
            editDialogVisible:false,
            editUserRules:{
                email:[
                    {
                        required:true,
                        message:'请输入email',
                        trriger:'blur'
                    },
                    {
                        validator:checkEmail,
                        trriger:'blur'
                    }
                ],
                mobile:[
                    {
                        required:true,
                        message:'请输入手机号码',
                        trriger:'blur'
                    },
                    {
                        validator:checkMobile,
                        trriger:'blur'
                    }
                ]
            },
            setRoleDialogVisible:false,
            userInfo:{},
            rolesList:[],
            roleId:''
        }
    },
    created(){
        this.getUserList();
    },
    methods:{
        async getUserList(){
            const {data:res} = await this.$http.get('users',{
                params:this.queryInfo
            })
            console.log(res)
            if(res.meta.status == 200){
                this.userList = res.data.users
                this.total = res.data.total
                this.queryInfo.pagenum = res.data.pagenum
                // this.queryInfo.pagesize = res.data.pagesize
            }else{
                this.$message.error(res.meta.msg);
            }
        },
        async showEditDialog(row){
            // console.log(row)
            const {data:res} = await this.$http.get(`users/${row.id}`);
            if(res.meta.status === 200){
                this.editUserForm = res.data
            }else{
                this.$message.error(res.meta.msg);
            }
            this.editDialogVisible = true;
        },
        async removeUserById(row){
            const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).catch(err => err)
                // 如果确认删除，返回confirm
                // 如果取消删除，返回cancel（因为catch(err => err)）
                if(confirmResult == 'confirm'){
                    const {data:res} = await this.$http.delete(`users/${row.id}`)
                    if(res.meta.status == 200){
                        this.$message.success(res.meta.msg)
                        this.getUserList()
                    }
                }else{
                    this.$message.info('取消删除')
                }
        },
        settring(row){

        },
        handleSizeChange(num){
            this.queryInfo.pagesize = num;
            this.getUserList();
        },
        handleCurrentChange(num){
            this.queryInfo.pagenum = num;
            this.getUserList();

        },
        async userStateChanged(userinfo){
            console.log(userinfo);
            const {data:res} = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
            console.log(res)
            if(res.meta.status !== 200){
                userinfo.mg_state = !userinfo.mg_state
                this.$message.error('更新用户状态失败')
            }else{
                this.$message.success('更新用户信息成功')
            }
            // this.getUserList()
        },
        addDialogClosed(){
            console.log('addDialogClosed method');
            this.$refs.addUserRef.resetFields();
        },
        editDialogClosed(){
            console.log('editDialogClosed method');
            this.$refs.editUserRef.resetFields();
        },
        addUser(){
            this.addDialogVisible = false;
            this.$refs.addUserRef.validate(async(valid)=>{
                console.log(valid);
                if(valid){
                    const {data:res} = await this.$http.post('users',this.addUserForm);
                    if(res.meta.status == 201){
                        this.$message.success('添加成功')
                        this.getUserList();
                        this.addDialogVisible = false;
                    }else{
                        this.$message.error(res.meta.msg)
                    }
                }else{
                    return;
                }
            })
        },
        editUser(){
            this.$refs.editUserRef.validate(async (valid)=>{
                console.log(valid);
                if(valid){
                    const {data:res} = await this.$http.put(`users/${this.editUserForm.id}`,{
                        email:this.editUserForm.email,
                        mobile:this.editUserForm.mobile
                    });
                    if(res.meta.status == 200){
                        this.$message.success(res.meta.msg)
                        this.getUserList();
                        this.editDialogVisible = false;
                    }else{
                        this.$message.error(res.meta.msg)
                    }
                }else{
                    return;
                }
            })
        },
        setRoleDialogClosed(){
            this.roleId = ''
        },
        async setRoles(){
            if(!this.roleId){
                this.$message.warning('请选择要分配的角色')
            }
            const {data:res} = await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.roleId});
            if(res.meta.status == 200){
                this.$message.success(res.meta.msg)
                this.getUserList();
            }else{
                this.$msessage.error(res.meta.msg)
            }
            this.setRoleDialogVisible = false;
        },
        async setting(row){
            this.userInfo = row;
            const {data:res} = await this.$http.get('roles');
            if(res.meta.status == 200){
                this.$message.success(res.meta.msg)
                this.rolesList = res.data;
            }else{
                this.$message.error(res.meta.msg)
            }
            this.setRoleDialogVisible = true;
        }
    }
}
</script>
<style lang="less" scoped>

</style>